import { defineComponent } from "../../src"


export default defineComponent(props => {
    const columns = ['name', 'power']
    const data = [
        { name: 'Chunk Norris', power: Infinity },
        { name: 'Bruce Lee', power: 9000 },
        { name: 'Jackie Chan', power: 7000 },
        { name: 'Jet Li', power: 8000 }
    ]

    return {
        template: `
        <form id="search">Search <input name="query" v-model="query"/></form>
        <table v-if="filteredData.length">
            <thead>
                <tr>
                    <th
                      v-for="column in columns"
                      :class="{ active: sortKey === column }"
                      @click="sortBy(column)"
                    >
                        {{ capitalize(column) }}
                        <span class="arrow" :class="sortOrders[column] > 0 ? 'asc' : 'dsc'"></span>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="entry in filteredData">
                    <td v-for="column in columns">{{ entry[column] }}</td>
                </tr>
            </tbody>
        </table>
        <p v-else>No matches found.</p>
        `,
        data() {
            return {
                query: '',
                columns,
                data,
                sortKey: '',
                sortOrders: columns.reduce((o, key) => ((o[key] = 1), o), {}),

                get filteredData() {
                    const sortKey = this.sortKey
                    const filterKey = this.query && this.query.toLowerCase()
                    const order = this.sortOrders[sortKey] || 1
                    let data = this.data
                    if (filterKey) {
                        data = data.filter(row => Object.keys(row).some(
                            key => String(row[key]).toLowerCase().indexOf(filterKey) !== -1
                        ))
                    }
                    if (sortKey) {
                        data = data.sort((a, b) => {
                            a = a[sortKey]
                            b = b[sortKey]

                            return (a === b ? 0 : a > b ? 1 : -1) * order
                        })
                    }

                    return data
                }
            }
        },
        sortBy(column) {
            this.sortKey = column
            this.sortOrders[column] = this.sortOrders[column] * -1
        },
        capitalize(column) {
            return column[0].toUpperCase() + column.slice(1)
        }
    }
})